<?php
require_once('Core/Model/Function/Abstract.php');

require_once('Core/Model/Table/Post.php');

class Core_Model_Function_Post extends Core_Model_Function_Abstract
{
    protected $_tablePost = null;

    public function __construct()
    {
        $this->_tablePost = new Core_Model_Table_Post;
    }

    public function findAll()
    {
        $result = array();
        /*
        $this->_tablePost->getAdapter()->setFetchMode(Zend_Db::FETCH_BOTH);
        $posts = $this->_tablePost->getAdapter()->fetchAll('SELECT * FROM kbs_post');
        var_dump($posts);
        */

        /*
        $db = Zend::initDb();
        echo $db->select()
                ->from(array('p' => 'mydb.product'), 
                       array('productNum' => 'p.product_id', 'LOWER(b)'))
                //->from(array'o' => 'order'),
                      // array('oid' => 'o.order_id'))
                ->joinleft(array('o' => 'order'), 'p.product_order = o.order_product_id', array('orderTimes' => 'COUNT(o.order_times)'))
                ->where('p.price > 100')
                ->group('p.product_id')
                ->order(array('orderTimes DESC', 'product_id'))
                ->limit(10, 2);
        */

        $posts = $this->_tablePost->fetchAll();

        if (null != $posts) {
            foreach ($posts as $post) {
                $author = $post->findDependentRowset('Core_Model_Table_User')->current();
                $result[] = array_merge($post->toArray(), $author->toArray());
            }
        }

        return $result;
    }

    public function findPostById($id)
    {
        $result = array();
        $post = $this->_tablePost->find($id)->current();
        if (null != $post) {
            $author = $post->findDependentRowset('Core_Model_Table_User')->current();
            $result = array_merge($post->toArray(), $author->toArray());
        }
        return $result;
    }

    public function save($data, $id = null)
    {
        if (null == $id) {
            $this->_tablePost->insert($data);
        } elseif (!empty($id)) {
            $db = $this->_tablePost->getAdapter();
            $where = $db->quoteInto('post_id = ?', $id);
            $this->_tablePost->update($data, $where);
        }
    }

    public function delete($id)
    {
        $db = $this->_tablePost->getAdapter();
        $where = $db->quoteInto('post_id = ?', $id);
        $this->_tablePost->delete($where);
    }

}